﻿Public Class HDAlarmForm

    Private Sub HDAlarmForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.DataGridView1.AutoGenerateColumns = False

        'For i As Integer = 0 To Me.DataGridView1.Columns.Count - 1
        '    Me.DataGridView1.Columns(i).SortMode = DataGridViewColumnSortMode.NotSortable
        'Next

        dtpTo.Value = UtilityClass.GetDateString(Now)
        dtpFrom.Value = dtpTo.Value.AddDays(-1).ToLongDateString()

        LoadRef()
    End Sub

    Private Sub LoadRef()
        Dim rts As RefTypeService = New RefTypeService(MainForm.pi)

        For Each rti As RefTypeItem In rts.GeRefGroupList()
            cboRef.Items.Add(rti)
        Next

        cboRef.SelectedIndex = -1
        btnRefresh.Enabled = False
        btnExport.Enabled = False
    End Sub

    ''' <summary>
    ''' 刷新数据
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    ''' 
    Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefresh.Click
        If sender.Text = "取消" Then
            sender.Text = "正在取消..."
            sender.Enabled = False
            bwSearch.CancelAsync()
            Exit Sub
        End If

        If CheckValidate() = False Then
            Exit Sub
        End If

        Me.DataGridView1.DataSource = Nothing
        Me.DataGridView1.Columns.Clear()

        'Me.DataGridView1.Cursor = Cursors.WaitCursor
        'Me.btnRefresh.Enabled = False
        Me.btnRefresh.Text = "取消"
        Me.cboRef.Enabled = False
        Me.dtpFrom.Enabled = False
        Me.dtpTo.Enabled = False
        Me.btnExport.Enabled = False
        Me.pnlSearch.Visible = True
        Me.bwSearch.RunWorkerAsync(cboRef.SelectedItem)
        'RefreshData()
        'Me.dtpFrom.Enabled = True
        'Me.dtpTo.Enabled = True

        'Me.btnRefresh.Enabled = True
        'Me.DataGridView1.Cursor = Cursors.Default

    End Sub

    ''' <summary>
    ''' 刷新数据
    ''' </summary>
    ''' <remarks></remarks>
    Private Function RefreshData(ByVal argument As Object) As Object
        Dim strSql As String
        Dim m_str As String
        'Dim m_index As Integer
        Dim proIndex As Integer
        Dim m_alarmexis As Boolean = False

        Dim cbo_rti As RefTypeItem = argument 'CType(cboRef.SelectedItem, RefTypeItem)
        Dim apts As AiPortTypeService = New AiPortTypeService(cbo_rti)
        Dim Port1, Port2 As Integer
        Dim col As String = ""
        Dim m_ailist As IList(Of Integer) = New List(Of Integer)
        Dim alarmstatus_DoorValid As Boolean = False
        Dim alarmstatus_LosPowerValid As Boolean = False

        m_ailist.Clear()

        'Me.DataGridView1.Columns.Clear()

        strSql = String.Format("select startTime")

        'm_index = Me.DataGridView1.Columns.Add("startTime", "时间")
        'Me.DataGridView1.Columns(m_index).DataPropertyName = "startTime"
        'Me.DataGridView1.Columns(m_index).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells


        For Each apti As AiPortTypeItem In apts.GetAiGroupList()
            If String.IsNullOrEmpty(apti.PortName) = False AndAlso apti.PortNo <> 0 Then '如果AI名称不为空并且端口号不为0
                Port1 = apti.PortNo * 2 - 1
                Port2 = apti.PortNo * 2
                strSql &= String.Format(",{0},{1}", "A" & Trim(Port1.ToString), "A" & Trim(Port2.ToString))
                'm_index = Me.DataGridView1.Columns.Add("A" & Trim(Port1.ToString), apti.PortName & "超高报警")
                'Me.DataGridView1.Columns(m_index).DataPropertyName = "A" & Trim(Port1.ToString)
                'm_index = Me.DataGridView1.Columns.Add("A" & Trim(Port2.ToString), apti.PortName & "超低报警")
                'Me.DataGridView1.Columns(m_index).DataPropertyName = "A" & Trim(Port2.ToString)
                m_ailist.Add(Port1)
                m_ailist.Add(Port2)
            End If
        Next

        'If is_firstrun = True Then '当前冷库没有配置AI
        '    msg.Show("指定冷库尚未配置数据端口")
        'End If

        Dim tablename_DoorAlarm = String.Format("Ref{0}_DoorAlarm", cbo_rti.RefId.ToString())
        Dim tablename_LostPowerAlarm = String.Format("Ref{0}_LostPowerAlarm", cbo_rti.RefId.ToString())

        Dim diopts As DiDoPortTypeService = New DiDoPortTypeService(cbo_rti)

        For Each diopti As DiDoPortTypeItem In diopts.GetDioGroupList()
            If diopti.DoorStatusPort >= 1 Then
                strSql &= String.Format("," & tablename_DoorAlarm)
                'm_index = Me.DataGridView1.Columns.Add(tablename_DoorAlarm, "库门报警")
                'Me.DataGridView1.Columns(m_index).DataPropertyName = tablename_DoorAlarm
                alarmstatus_DoorValid = True
            End If

            If diopti.LostPowerPort >= 1 Then
                strSql &= String.Format("," & tablename_LostPowerAlarm)
                'm_index = Me.DataGridView1.Columns.Add(tablename_LostPowerAlarm, "缺项报警")
                'Me.DataGridView1.Columns(m_index).DataPropertyName = tablename_LostPowerAlarm
                alarmstatus_LosPowerValid = True
            End If
        Next

        strSql &= String.Format(" From tbccHDAlarmData_{0} Where startTime>='{1}' and startTime<='{2}' and netID='{3}' order by startTime", cbo_rti.ProjectID.Replace("-", "_"), UtilityClass.GetDateString(Me.dtpFrom.Value), UtilityClass.GetDateString(Me.dtpTo.Value), cbo_rti.NetId)

        Dim ds As DataSet = Nothing
        ds = SqlHelper.ExecuteDataset(strSql, Nothing)

        proIndex = 0
        For Each r As DataRow In ds.Tables(0).Rows
            If Me.bwSearch.CancellationPending Then '取消查询
                ds.Clear() : ds.Dispose() : ds = Nothing
                Return Nothing
            End If
            If alarmstatus_DoorValid = True Then
                If Not IsDBNull(r(tablename_DoorAlarm)) Then '库门开关状态
                    If r(tablename_DoorAlarm) = g_On.ToString() Then
                        r(tablename_DoorAlarm) = "报警"
                    Else
                        r(tablename_DoorAlarm) = "正常"
                    End If
                End If
            End If

            If alarmstatus_LosPowerValid = True Then
                If Not IsDBNull(r(tablename_LostPowerAlarm)) Then '缺项报警状态
                    If r(tablename_LostPowerAlarm) = g_On Then
                        r(tablename_LostPowerAlarm) = "报警"
                    Else
                        r(tablename_LostPowerAlarm) = "正常"

                    End If
                End If
            End If

            For Each item As Integer In m_ailist '处理当前冷库存在的AI数据
                col = "A" + item.ToString()
                If Not IsDBNull(r(col)) Then
                    If r(col) = g_On.ToString() Then
                        r(col) = "报警"
                    Else
                        r(col) = "正常"
                    End If
                End If
            Next
            proIndex += 1
            ReportProgress((proIndex / ds.Tables(0).Rows.Count) * 100) '进度报告
        Next

        ds.AcceptChanges()


        m_ailist.Clear()  '临时使用

        For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
            If Me.bwSearch.CancellationPending Then '取消查询
                ds.Clear() : ds.Dispose() : ds = Nothing
                Return Nothing
            End If

            m_alarmexis = False

            For j As Integer = 0 To ds.Tables(0).Columns.Count - 1

                m_str = ds.Tables(0).Rows(i).Item(j)

                If i = 0 Then '第一条报警
                    If m_str.IndexOf("报警") >= 0 Then
                        m_alarmexis = True '当前冷库存在报警(由于报警信息是根据设备进行保存的,对于某一设备中存在报警,而该设备中的某一冷库无报警的情况进行处理)
                        Exit For
                    End If
                ElseIf i > 0 AndAlso j > 0 Then  '对当前冷库中报警存在,但并未发生改变,而其它设备的报警信息发生变化而导致当前库检索结果重复的情况进行处理
                    If m_str <> ds.Tables(0).Rows(i - 1).Item(j) Then '两条报警记录不相同
                        m_alarmexis = True
                        Exit For
                    End If
                End If
            Next

            If m_alarmexis = False Then '删除重复的报警记录
                m_ailist.Add(i)
            End If

            ReportProgress((i / ds.Tables(0).Rows.Count) * 100) '进度报告
        Next

        For Each item As Integer In m_ailist
            ds.Tables(0).Rows(CInt(item)).Delete()
        Next

        ds.AcceptChanges()

        If ds.Tables(0).Rows.Count <= 0 Then
            ds.Clear() : ds.Dispose() : ds = Nothing
            Return Nothing
        End If

        'Me.DataGridView1.DataSource = ds.Tables(0)

        'For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
        '    For j As Integer = 1 To Me.DataGridView1.Columns.Count - 1
        '        If Convert.ToString(Me.DataGridView1.Rows(i).Cells(j).Value) = "报警" Then
        '            Me.DataGridView1.Rows(i).Cells(j).Style.ForeColor = Color.Red
        '        End If
        '    Next
        'Next

        'Me.btnExport.Enabled = True

        Return ds
    End Function

    ''' <summary>
    ''' 检查时间范围是否合法
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CheckValidate() As Boolean
        If Me.dtpTo.Value < Me.dtpFrom.Value Then
            msg.ShowWarning("起始时间不能大于终止时间")
            Me.dtpFrom.Focus()
            Return False
        End If


        If cboRef.SelectedIndex = -1 Then
            msg.ShowWarning("请选择冷库")
            Me.cboRef.Focus()
            Return False
        End If

        Return True
    End Function

    Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click
        Export()
    End Sub

    Private Sub Export()
        Dim dt As DataTable
        dt = CType(Me.DataGridView1.DataSource, DataTable)
        If dt Is Nothing OrElse dt.Rows.Count = 0 Then
            msg.Show("没有数据")
            Exit Sub
        End If

        Dim excel As New Excel.Application

        'excel.Workbooks.Open(_excelFile)
        excel.Workbooks.Add()

        '  excel.Application.Workbooks.Add(True)
        excel.Visible = True
        Dim values(dt.Rows.Count, dt.Columns.Count) As Object

        For j As Integer = 0 To Me.DataGridView1.Columns.Count - 1
            values(0, j) = Me.DataGridView1.Columns(j).HeaderText
        Next

        Dim strCol As String
        For i As Integer = 0 To dt.Rows.Count - 1
            Dim r As DataRow = dt.Rows(i)
            For j As Integer = 0 To Me.DataGridView1.Columns.Count - 1
                strCol = Me.DataGridView1.Columns(j).DataPropertyName
                values(i + 1, j) = r(strCol)
            Next
        Next

        Try
            excel.Range(excel.Cells(1, 1), excel.Cells(dt.Rows.Count + 1, dt.Columns.Count)).Value = values
            'excel.Workbooks(1).PrintOut()
            'excel.DisplayAlerts = False
            'excel.Quit()
        Catch ex As Exception
            Debug.WriteLine(ex.ToString())
        End Try
    End Sub

    Private Sub DataGridView1_Sorted(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.Sorted
        For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
            For j As Integer = 1 To Me.DataGridView1.Columns.Count - 1
                If Me.DataGridView1.Rows(i).Cells(j).Value = "报警" Then
                    Me.DataGridView1.Rows(i).Cells(j).Style.ForeColor = Color.Red
                End If
            Next
        Next
    End Sub

    Private Sub cboRef_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboRef.SelectedIndexChanged
        If CType(sender, ComboBox).SelectedIndex <> -1 Then
            btnRefresh.Enabled = True

        End If
    End Sub

    Private Sub bwSearch_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwSearch.DoWork
        Dim ds As DataSet
        e.Result = New Object() {True, Nothing}

        '设置状态
        Dim str As String = String.Format("正在查询{0}历史报警数据……", e.Argument)
        If Me.InvokeRequired Then
            Me.Invoke(New VoidMethodHandler(AddressOf SetSearchState), str)
        Else
            SetSearchState(str)
        End If

        '查询数据
        ds = RefreshData(e.Argument)

        '添加数据至DataGridView
        If ds IsNot Nothing Then
            Dim obj As Object = New Object() {e.Argument, ds}
            If Me.InvokeRequired Then
                Me.Invoke(New VoidMethodHandler(AddressOf AddDataToGridView), obj)
            Else
                AddDataToGridView(obj)
            End If
        Else
            e.Result(0) = False '无数据
        End If

        e.Result(1) = Me.bwSearch.CancellationPending
    End Sub

    Private Delegate Sub VoidMethodHandler(ByVal obj As Object)
    Private Sub bwSearch_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bwSearch.ProgressChanged
        Me.pbSearch.Value = e.ProgressPercentage
    End Sub

    Private Sub bwSearch_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bwSearch.RunWorkerCompleted
        Me.pnlSearch.Visible = False

        If e.Result(0) = True Then
            Me.btnExport.Enabled = True
        ElseIf Not e.Result(1) Then '过滤取消操作
            Me.btnExport.Enabled = False
            msg.Show("指定时间范围没有数据,请重新设置")
        End If

        Me.dtpFrom.Enabled = True
        Me.dtpTo.Enabled = True
        Me.cboRef.Enabled = True
        Me.btnRefresh.Enabled = True
        Me.btnRefresh.Text = "查询"
        'Me.DataGridView1.Cursor = Cursors.Default
        GC.Collect()

        If e.Result(1) Then
            msg.Show("操作已取消")
        End If

    End Sub
    Private Sub AddDataGridViewColumns(ByVal obj As Object)
        Dim m_index As Integer
        Dim Port1, Port2 As Integer
        Dim cbo_rti As RefTypeItem = obj
        Dim apts As AiPortTypeService = New AiPortTypeService(cbo_rti)

        'Time
        m_index = Me.DataGridView1.Columns.Add("startTime", "时间")
        Me.DataGridView1.Columns(m_index).DataPropertyName = "startTime"
        Me.DataGridView1.Columns(m_index).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells

        'AI
        For Each apti As AiPortTypeItem In apts.GetAiGroupList()
            If String.IsNullOrEmpty(apti.PortName) = False AndAlso apti.PortNo <> 0 Then '如果AI名称不为空并且端口号不为0
                Port1 = apti.PortNo * 2 - 1
                Port2 = apti.PortNo * 2
                m_index = Me.DataGridView1.Columns.Add("A" & Trim(Port1.ToString), apti.PortName & "超高报警")
                Me.DataGridView1.Columns(m_index).DataPropertyName = "A" & Trim(Port1.ToString)
                m_index = Me.DataGridView1.Columns.Add("A" & Trim(Port2.ToString), apti.PortName & "超低报警")
                Me.DataGridView1.Columns(m_index).DataPropertyName = "A" & Trim(Port2.ToString)
            End If
        Next

        'DIO
        Dim tablename_DoorAlarm = String.Format("Ref{0}_DoorAlarm", cbo_rti.RefId.ToString())
        Dim tablename_LostPowerAlarm = String.Format("Ref{0}_LostPowerAlarm", cbo_rti.RefId.ToString())

        Dim diopts As DiDoPortTypeService = New DiDoPortTypeService(cbo_rti)

        For Each diopti As DiDoPortTypeItem In diopts.GetDioGroupList()
            If diopti.DoorStatusPort >= 1 Then
                m_index = Me.DataGridView1.Columns.Add(tablename_DoorAlarm, "库门报警")
                Me.DataGridView1.Columns(m_index).DataPropertyName = tablename_DoorAlarm
            End If

            If diopti.LostPowerPort >= 1 Then
                m_index = Me.DataGridView1.Columns.Add(tablename_LostPowerAlarm, "缺项报警")
                Me.DataGridView1.Columns(m_index).DataPropertyName = tablename_LostPowerAlarm
            End If
        Next

    End Sub
    Private Sub AddDataToGridView(ByVal obj As Object)
        AddDataGridViewColumns(obj(0))
        Me.DataGridView1.DataSource = obj(1).Tables(0)

        For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
            For j As Integer = 1 To Me.DataGridView1.Columns.Count - 1
                If Convert.ToString(Me.DataGridView1.Rows(i).Cells(j).Value) = "报警" Then
                    Me.DataGridView1.Rows(i).Cells(j).Style.ForeColor = Color.Red
                End If
            Next
        Next

    End Sub
    Private Sub SetSearchState(ByVal obj As Object)
        Me.lblSearchState.Text = obj
    End Sub
    Private Sub ReportProgress(ByVal value As Integer)
        If Me.InvokeRequired Then
            Me.Invoke(New VoidMethodHandler(AddressOf ReportProgressMethod), value)
        Else
            ReportProgressMethod(value)
        End If
    End Sub
    Private Sub ReportProgressMethod(ByVal obj As Object)
        Me.bwSearch.ReportProgress(obj)
    End Sub

    Private Sub HDAlarmForm_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        DisposeBackWorker()
    End Sub

    Private Sub DisposeBackWorker()
        If Me.bwSearch IsNot Nothing Then
            Me.bwSearch.CancelAsync()
            Me.bwSearch.Dispose() : Me.bwSearch = Nothing
        End If
        GC.Collect()
    End Sub
End Class